package com.yanqu.road.server.manager.activity.suitang.task;

import com.yanqu.road.entity.activity.suitang.enums.eSuiTangTaskType;
import com.yanqu.road.entity.enums.eTongBingTaskType;
import com.yanqu.road.server.manager.activity.suitang.activity.CrossSuiTangActivity;
import com.yanqu.road.server.manager.activity.tongbing.activity.CrossTongBingActivity;
import com.yanqu.road.utils.date.DateHelper;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public abstract class BaseCrossSuiTangTask implements Runnable, Delayed {

    protected CrossSuiTangActivity activity;
    protected long createTime;
    protected long beginTime;
    protected long finishTime;
    protected boolean once;      // 是否循环任务
    protected long runnableTime; // 循环间隔时间，默认1秒

    public BaseCrossSuiTangTask(CrossSuiTangActivity activity, long beginTime, boolean once, long runnableTime) {
        this.activity = activity;
        this.beginTime = beginTime;
        this.createTime = System.currentTimeMillis();
        this.once = once;
        this.runnableTime = runnableTime;
    }

    public BaseCrossSuiTangTask(CrossSuiTangActivity activity, long beginTime, boolean once) {
        this.activity = activity;
        this.beginTime = beginTime;
        this.createTime = System.currentTimeMillis();
        this.once = once;
        this.runnableTime = DateHelper.SECOND_MILLIONS;
    }

    public BaseCrossSuiTangTask(CrossSuiTangActivity activity, long beginTime) {
        this.activity = activity;
        this.beginTime = beginTime;
        this.createTime = System.currentTimeMillis();
        this.once = true;
        this.runnableTime = DateHelper.SECOND_MILLIONS;
    }

    // ======================== Runnable ============================

    @Override
    public void run() {
        runTask();
        this.finishTime = System.currentTimeMillis();
    }

    // ======================== Delayed ============================

    @Override
    public int compareTo(Delayed o) {
        BaseCrossSuiTangTask delayedTask = (BaseCrossSuiTangTask) o;
        return Long.compare(getBeginTime(), delayedTask.getBeginTime());
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(getBeginTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    public long getBeginTime() {
        return beginTime;
    }

    public void setBeginTime(long beginTime) {
        this.beginTime = beginTime;
    }

    public boolean isOnce() {
        return once;
    }

    public long getFinishTime() {
        return finishTime;
    }

    public long getRunnableTime() {
        return runnableTime;
    }

    public abstract void runTask();

    public abstract String getId();

    public abstract eSuiTangTaskType getType();

}
